<template>
  <div class="temperature-statistics pad">
    <h2>{{ this.selectedSchool }}</h2>

    <div class="bread_crumbs">
      <div class="bread">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <!--        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
          <el-breadcrumb-item>{{ this.selectedSchool }}</el-breadcrumb-item>
          <el-breadcrumb-item>体温打卡统计</el-breadcrumb-item>
          <!--        <el-breadcrumb-item>活动详情</el-breadcrumb-item>-->
        </el-breadcrumb>
      </div>
    </div>

    <div class="search_temp">
      <div class="search_grade">
        <!-- <el-select
          v-model="selectedSchool"
          clearable
          filterable
          placeholder="请选择学校"
          :loading="schoolLoading"
          @change="schoolInput"
          :disabled="canSelect"
        >
          <el-option v-for="(item, i) in schools" :key="i" :value="item.enterpriseName" :label="item.enterpriseName"></el-option>
        </el-select> -->
        <span style="padding-right: 20px;">起止日期 </span>
        <el-date-picker v-model="dateArr" type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH-mm-ss" size="mini"
          @change="dateChage">
        </el-date-picker>

        <!--        <el-button type=primary-->
        <!--                   @click="exportPDF"-->
        <!--                   :loading="exportLoading"-->
        <!--                   v-if="statisticsList.length">-->
        <!--          <i class="el-icon-download"></i>-->
        <!--          导出Excel-->
        <!--        </el-button>-->

        <!--        年级-->
        <span>年级 </span>
        <el-select
          v-model="selectedGrade"
          clearable
          filterable
          :loading="gradeLoading"
          placeholder="请选择年级"
          style="margin: 0 20px;"
          @change="gradeInput"
          size="mini"
        >
          <el-option v-for="(item, i) in grades" :key="i" :value="item.grade" :label="item.grade"></el-option>
        </el-select>
        <!--        班级-->
        <span> 班级 </span>
        <el-select
          v-model="selectedClass"
          clearable
          filterable
          :loading="classLoading"
          placeholder="请选择班级"
          @change="classInput"
          size="mini"
        >
          <el-option v-for="(item, i) in classes" :key="i" :value="item.grades" :label="item.grades"></el-option>
        </el-select>
        <el-button size="mini" type=primary @click="searchSchool">
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
    </div>

    <!--    <div class="split-line" v-if="selectedSchool">-->
    <!--      <div>-->
    <!--        <span>{{ selectedSchool }}</span>-->
    <!--        <span v-if="selectedGrade"> - {{ selectedGrade }}</span>-->
    <!--        <span v-if="selectedClass"> - {{ selectedClass }}</span>-->
    <!--        &lt;!&ndash; <span v-if="peopleNum === 0 || peopleNum">({{peopleNum}}人)</span> &ndash;&gt;-->
    <!--      </div>-->
    <!--    </div>-->

    <p
      style="padding-top: 50px; text-align: center; color: #dedede;"
      v-if="!statisticsList.length"
    >暂无统计数据</p>
    <div v-if="statisticsList.length" class="pdf-box" ref="temperature">
      <div class="place-div"></div>
      <div style="flex: 1">
        <div
          v-for="(item, index) in statisticsList"
          :key="index"
        >
          <h1 style="text-align: center; font-weight: bold; background-color: #dedede; padding: 8px 0;">
            {{ item.gradeName }}</h1>
          <div
            v-for="(list, date) in item"
            :key="date + index"
          >
            <div v-if="date !== 'gradeName'">
              <h2 style="text-align: center; background-color: #f5f5f5; padding: 8px 0; font-weight: bold;">
                {{ date }}</h2>
              <div style="display: flex;">
                <span
                  style="width: 260px; flex-shrink: 0; border-style: solid; border-width: 0 1px 1px 1px; border-color: #f5f5f5;"></span>
                <div style="display: flex; flex: 1">
                  <span
                    v-for="(tt, aa) in hourRange"
                    :key="aa"
                    style="flex: 1; text-align: center; padding: 10px 0; font-weight: bold; border-style: solid; border-color:  #f5f5f5; border-width: 0 1px 1px 0"
                  >{{ tt }}</span>
                </div>
              </div>
              <div
                v-for="(s, i) in list"
                :key="i"
                style="display: flex;"
                class="t-list-i"
              >
                <div style="display: flex; width: 260px; flex-shrink: 0;">
                  <span
                    style="flex: 1; text-align: center; padding: 10px 0; border-style: solid; border-width: 0 1px 1px 1px; border-color: #f5f5f5;">{{
                      s.name
                    }}</span>
                  <span
                    style="flex: 1; text-align: center; padding: 10px 0; border-style: solid; border-width: 0 1px 1px 0; border-color: #f5f5f5;">{{
                      s.gender == '1' ? '男' : '女'
                    }}</span>
                  <span
                    style="flex: 1; text-align: center; padding: 10px 0; border-style: solid; border-width: 0 1px 1px 0; border-color: #f5f5f5;">{{
                      s.age
                    }}岁</span>
                  <span
                    style="flex: 1; text-align: center; padding: 10px 0; border-style: solid; border-width: 0 1px 1px 0; border-color: #f5f5f5;">{{
                      s.className
                    }}</span>
                  <span
                    style="flex: 1; text-align: center; padding: 10px 0; border-style: solid; border-width: 0 1px 1px 0; border-color: #f5f5f5;">{{
                      s.sno
                    }}</span>
                </div>
                <div style="display: flex; flex: 1">
                  <span
                    v-for="(t, ii) in hourRange"
                    :key="ii"
                    :style="{flex: 1, 'text-align': 'center', padding: '10px 0', color: s[t] > 37 ? 'red' : '#2c3e50', 'font-weight': s[t] > 37 ? 'bold' : 'normal', 'border-style': 'solid', 'border-color': '#f5f5f5', 'border-width': '0 1px 1px 0'}"
                  >{{ s[t] ? s[t] + '℃' : '' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="place-div"></div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import {
  getAllSchool,
  getGradesBySchoolName,
  getClassBySchoolAndGrade,
  getTemperatureStatistics
} from '../api';
import {
  getSchoolInfo,
  getMemberTemperatureDataPage,
  getMemberTemperatureData
} from '../api/version2';
import {formatDate} from '../util/index';
import json2Excel from '../util/json2Excel';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import html2canvas from 'html2canvas';
import {jsPDF} from 'jspdf';

export default {
  name: '',
  data() {
    const startHour = 8;
    const endHour = 18;
    const hourRange = Array(endHour - startHour + 1).fill(1).map((item, index) => {
      let r = index + startHour;
      return `${r < 10 ? '0' : ''}${r}:00`
    });
    return {
      whiteKeyList: ['age', 'className', 'gender', 'memberId', 'name', 'relationship', 'sno', 'wechatName'],
      hourRange,
      dateArr: '',
      type: 1,
      selectedSchool: '',
      selectedGrade: '',
      selectedClass: '',
      schoolLoading: false,
      gradeLoading: false,
      classLoading: false,
      schools: [],
      grades: [],
      classes: [],
      totalArr: [], // 概述
      noCardMembers: [], // 未打卡人员
      noCardNum: 0, // 未打卡人数
      cardMembers: [], // 已打卡人员
      badCardMembers: [], // 异常打卡人员
      showAllName: true,
      showGood: true,
      showBad: true,
      canSelect: false,
      hostName: '',
      consumeType: 1, // 统计类型 1: 学校 2: 公司 3: 医院
      resultList: [],

      temperatureList: [],
      temperatureLoading: false,
      temperatureTotal: 0,
      exportLoading: false,
      pageSize: 10,
      statisticsList: [],

    }
  },
  methods: {
    schoolInput() { // 学校输入
      this.resetData();
      this.selectedGrade = '';
      this.selectedClass = '';
      this.grades = [];
      this.classes = [];
      if (this.selectedSchool) {
        this.fetchSchoolList(this.selectedSchool, null)
      }
    },
    dateChage() {
      this.resetData()
    },
    rowStyle(row) {
      // console.log(row)
    },
    rgb() {//rgb颜色随机
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      var rgb = 'rgb(' + r + ',' + g + ',' + b + ')';
      return rgb;
    },
    gradeInput() { // 年级输入
      this.resetData();
      this.selectedClass = '';
      this.classes = [];
      if (this.selectedGrade) {
        this.fetchSchoolList(this.selectedSchool, this.selectedGrade)
      }
    },
    exportPDF() { // 导出pdf
      const that = this;
      this.exportLoading = true;
      html2canvas(this.$refs.temperature, {})
        .then(canvas => {

          try {
            var contentWidth = canvas.width;
            var contentHeight = canvas.height;

            //一页pdf显示html页面生成的canvas高度;
            var pageHeight = contentWidth / 592.28 * 841.89;
            //未生成pdf的html页面高度
            var leftHeight = contentHeight;
            //页面偏移
            var position = 10;
            //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            var imgWidth = 595.28;
            var imgHeight = 592.28 / contentWidth * contentHeight;

            var pageData = canvas.toDataURL('image/jpeg', 1.0);
            var pdf = new jsPDF('', 'pt', 'a4');

            //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
            //当内容未超过pdf一页显示的范围，无需分页
            if (leftHeight < pageHeight) {
              pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
            } else {
              while (leftHeight > 0) {
                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                leftHeight -= pageHeight;
                position -= 841.89;
                //避免添加空白页
                if (leftHeight > 0) {
                  pdf.addPage();
                }
              }
            }

            this.exportLoading = false;
            let title = '';
            if (!this.selectedGrade) {
              title = `${this.selectedSchool}(${this.dateArr[0]}至${this.dateArr[1]})体温统计`
            } else if (this.selectedGrade && !this.selectedClass) {
              title = `${this.selectedSchool} · ${this.selectedGrade}(${this.dateArr[0]}至${this.dateArr[1]})体温统计`
            } else if (this.selectedGrade && this.selectedClass) {
              title = `${this.selectedSchool} · ${this.selectedGrade} · ${this.selectedClass}(${this.dateArr[0]}至${this.dateArr[1]})体温统计`
            }
            ;
            pdf.save(`${title}.pdf`)
          } catch (e) {
          }
        })
        .catch(e => {
          this.$message.error(e);
          this.exportLoading = false
        })
    },
    resetData() {
      this.totalArr = [];
      this.noCardMembers = [];
      this.cardMembers = [];
      this.badCardMembers = []
    },
    handlePagi(page) { // 分页事件
      this.fetchTemperaturePagi(page)
    },
    searchSchool() { // 查询学校信息
      // if (!this.$checkAuth('canSeeSchoolTemperature')) {
      //   return this.$message.error('暂无对应操作权限!')
      // };
      if (!this.selectedSchool) {
        return this.$message.error('查询条件不能为空!')
      }
      ;
      if (!this.dateArr) {
        return this.$message.error('请选择查询时间段!')
      }
      ;
      if (this.selectedGrade && !this.selectedClass) { // 按照年级统计
        this.type = 2;
        this.hostName = `${this.selectedSchool}-${this.selectedGrade}年级`
      } else if (this.selectedGrade && this.selectedClass) { // 按照班级统计
        this.type = 3;
        this.hostName = `${this.selectedSchool}-${this.selectedGrade}年级-${this.selectedClass}班`
      } else if (!this.selectedGrade && !this.selectedClass) { // 按照学校统计
        this.type = 1;
        this.hostName = this.selectedSchool
      }
      ;
      this.fetchAllTemperature()
      // this.fetchTemperaturePagi(1)
      // return
      // this.fetchTemperatureStatistics(this.selectedSchool, this.selectedGrade, this.selectedClass)
    },
    exportExcel() { // 导出表格
      this.fetchAllTemperature()
    },
    exportNo() { // 导出excel
      if (!this.$checkAuth('canExportSchoolTemperature')) {
        return this.$message.error('暂无对应操作权限!')
      }
      ;
      let bigTitle = `${this.hostName} ${this.dateArr[0]}至${this.dateArr[1]}未打卡人员名单`;
      json2Excel(this.noCardMembers, bigTitle, ['姓名'], [], bigTitle)
    },
    exportNormal() { // 导出正常打卡人员记录
      if (!this.$checkAuth('canExportSchoolTemperature')) {
        return this.$message.error('暂无对应操作权限!')
      }
      ;
      let bigTitle = `${this.hostName} ${this.dateArr[0]}至${this.dateArr[1]}正常打卡人员名单`;
      json2Excel(this.cardMembers, bigTitle, ['打卡温度', '打卡地址', '打卡时间', '名称'], ['memberId'], bigTitle)
    },
    exportBad() { // 导出异常打卡人员记录
      if (!this.$checkAuth('canExportSchoolTemperature')) {
        return this.$message.error('暂无对应操作权限!')
      }
      ;
      let bigTitle = `${this.hostName} ${this.dateArr[0]}至${this.dateArr[1]}异常打卡人员名单`;
      json2Excel(this.badCardMembers, bigTitle, ['打卡温度', '打卡地址', '打卡时间', '名称'], ['memberId'], bigTitle)
    },
    fetchSchoolList(enterpriseName, grade) { // 查询学校列表
      getSchoolInfo({
        enterpriseName: enterpriseName || null,
        grade: grade || null,
        grades: null,
        type: this.consumeType
      })
        .then(res => {
          let list = res.data.data || [];
          list = list.filter(item => item);
          if (!enterpriseName) { // 查询所有学校
            this.schools = list
          } else if (enterpriseName && !grade) { // 查询年级
            this.grades = list
          } else if (enterpriseName && grade) { // 查询班级
            this.classes = list
          }
        })
        .catch(e => {

        })
    },
    fetchAllSchool() { // 获取学校信息
      this.schoolLoading = true;
      getAllSchool()
        .then(res => {
          this.schoolLoading = false;
          if (res.data.code === 1) {
            this.schools = res.data.data || []
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.schoolLoading = false;
          this.$message.error('网络异常!')
        })
    },
    fetchGrade(schoolName) { // 获取年级
      this.gradeLoading = true;
      getGradesBySchoolName(schoolName)
        .then(res => {
          this.gradeLoading = false;
          if (res.data.code === 1) {
            this.grades = res.data.data || []
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.gradeLoading = false;
          this.$message.error('网络异常!')
        })
    },
    fetchClass(schoolName, gradeName) { // 获取班级
      this.classLoading = true;
      getClassBySchoolAndGrade(schoolName, gradeName)
        .then(res => {
          this.classLoading = false;
          if (res.data.code === 1) {
            this.classes = res.data.data || []
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.classLoading = false;
          this.$message.error('网络异常!')
        })
    },
    classInput() {
      this.resetData()
    },
    fetchTemperatureStatistics(schoolName, gardeName, className) {
      NProgress.start();
      gardeName = gardeName || null;
      className = className || null;
      getTemperatureStatistics({
        type: this.type,
        schoolName,
        gardeName,
        className,
        inputStartTime: this.dateArr[0] + ' 00:00:00',
        inputEndTime: this.dateArr[1] + ' 23:59:59'
      })
        .then(res => {
          NProgress.done();
          if (res.data.code === 1) {
            let data = res.data.data;
            let tempArr = [];
            let name = '';
            switch (this.type) {
              case 1:
                name = `${this.selectedSchool}`;
                break
              case 2:
                name = `${this.selectedSchool}-${this.selectedGrade}年级`;
                break
              case 3:
                name = `${this.selectedSchool}-${this.selectedGrade}年级-${this.selectedClass}班`
            }
            ;
            tempArr.push({label: '统计主体名称', value: name});
            tempArr.push({label: '总打卡频次', value: data.allClockNum});
            tempArr.push({label: '未打卡人数', value: data.noClockNum});
            tempArr.push({label: '平均打卡率', value: data.averageRate + '%'});
            tempArr.push({label: '异常打卡率', value: data.badRate + '%'});
            this.totalArr = tempArr;
            this.noCardMembers = data.noClockMemberName.map(item => {
              return {
                name: item
              }
            });
            this.noCardNum = data.noClockNum;
            let cards = data.clockMemberTemperatures.map(item => {
              item.createDate = formatDate(item.createDate);
              return item
            });
            this.cardMembers = this.groupArr(cards);
            this.badCardMembers = data.badClockMemberTemperatures.map(item => {
              item.createDate = formatDate(item.createDate);
              return item
            })
            tempArr = null
          } else {
            this.$message.error('网络异常!')
          }
        })
        .catch(e => {
          NProgress.done();
          this.$message.error('网络异常!')
        })
    },
    groupArr(arr) {
      let tempObj = {};
      let tempArr = [];
      for (let i = 0; i < arr.length; i++) {
        if (!tempObj[arr[i].createDate]) {
          tempObj[arr[i].createDate] = [arr[i]];
        } else {
          tempObj[arr[i].createDate].push(arr[i])
        }
      }
      ;
      for (let key in tempObj) {
        for (let j = 0; j < tempObj[key].length; j++) {
          tempArr.push(tempObj[key][j])
        }
      }
      ;
      return tempArr
    },
    fetchTemperaturePagi(index) { // 分页查询体温统计
      this.temperatureLoading = true;
      getMemberTemperatureDataPage({
        index,
        count: this.pageSize,
        queryParam: {
          enterpriseName: this.selectedSchool,
          grade: this.selectedGrade || null,
          grades: this.selectedClass || null,
          startDate: this.dateArr[0],
          endDate: this.dateArr[1]
        }
      })
        .then(res => {
          this.temperatureLoading = false;
          let list = res.data.data.list || [];
          list.forEach(item => {
            item.createDate = formatDate(item.createDate, 'zh:')
          });
          this.temperatureList = list;
          this.temperatureTotal = res.data.data.totalRecord;
        })
        .catch(e => {
          this.temperatureLoading = false
        })
    },
    fetchAllTemperature() { // 查询所有体温
      this.temperatureLoading = true;
      getMemberTemperatureData({
        enterpriseName: this.selectedSchool,
        grade: this.selectedGrade || null,
        grades: this.selectedClass || null,
        startDate: this.dateArr[0],
        endDate: this.dateArr[1]
      })
        .then(res => {
          const list = res.data.data || [];
          list.forEach(item => {
            const h = new Date(item.createDate).getHours();
            item.timeStamp = item.createDate;
            item.createDate = formatDate(item.createDate, '-');
            item.time = `${h < 10 ? '0' : ''}${h}:00`
          });
          this.formatTemperatureData(list)
        })
        .catch(e => {
          this.temperatureLoading = false
        })
    },
    formatTemperatureData(list) { // 格式化体温数据
      console.time('format data needed:');
      this.temperatureLoading = true;
      const tempObj = {};
      const tempList = [];
      list.forEach(item => {
        let gradeKey = item.grade || '未知年级';
        if (!tempObj[gradeKey]) {
          tempObj[gradeKey] = [item]
        } else {
          tempObj[gradeKey].push(item)
        }
      });
      for (let key in tempObj) {
        let itemObj = {
          gradeName: key
        };
        tempObj[key].forEach(t => {
          if (!itemObj[t.createDate]) {
            itemObj[t.createDate] = [t]
          } else {
            itemObj[t.createDate].push(t)
          }
        });
        tempList.push(itemObj)
      }
      ;
      const newList = tempList.map(item => {
        let tObj = {
          gradeName: item.gradeName
        };
        for (let key in item) {
          let sObj = {};
          if (key !== 'gradeName') {
            tObj[key] = [];
            item[key].forEach(s => {
              let sKey = s.name + '&' + s.memberId;
              if (!sObj[sKey]) {
                sObj[sKey] = [s]
              } else {
                sObj[sKey].push(s)
              }
            })
          }
          ;
          for (let key1 in sObj) {
            let oo = {
              name: key1.split('&')[0],
              memberId: key1.split('&')[1]
            };
            sObj[key1].sort((a, b) => b.timeStamp - a.timeStamp);
            sObj[key1].forEach(ss => {
              oo[ss.time] = ss.recordValue;
              oo.className = ss.grades || '未知班级';
              oo.sno = ss.sno;
              oo.gender = ss.sex;
              oo.age = ss.age;
              oo.wechatName = ss.nickname;
              oo.relationship = ss.relationship
            });
            tObj[key].push(oo)
          }
          ;
        }
        ;
        return tObj
      });
      this.statisticsList = newList
      this.temperatureLoading = false
      console.timeEnd('format data needed:')
    }


  },
  created() {
    this.selectedSchool = this.$route.params.name;
    let roleId = sessionStorage.getItem('role');
    let name = sessionStorage.getItem('username');
    let roleTitle = sessionStorage.getItem('roleTitle');

    if (roleTitle == '学校') { // 学校
      this.consumeType = 1;
      this.canSelect = true;
      this.selectedSchool = name;
      this.fetchSchoolList(this.selectedSchool, null)
    } else if (roleTitle == '公司') { // 公司
      this.consumeType = 2;
      this.canSelect = true;
      this.selectedSchool = name
    } else {
      this.fetchSchoolList(this.selectedSchool, null);
    }
    ;
  }
}
</script>
<style lang="scss">
.pdf-box {
  display: flex;

}

.place-div {
  width: 48px;
  flex-shrink: 0;
}

.t-list-i {
  transition: .2s;
  cursor: pointer;

  &:hover {
    // background-color: #f9f9f9;
    border: 2px dashed red;
  }

}

.temperature-statistics {

  .no-statistics {
    margin-top: 50px;
    text-align: center;
    color: #707070;
  }

  .split-line {
    margin: 40px 0;
    position: relative;
    height: 2px;
    background-color: #4AC493;

    div {
      padding: 0 10px;
      position: absolute;
      display: inline-block;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      background-color: #ffffff;
      z-index: 3;

      span {
        color: #4AC493;
        font-size: 20px;
        font-weight: bold;
      }
    }
  }

  .t-title {
    margin: 30px 0 20px 0;
    display: inline-block;
    padding: 8px 20px;
    background-color: #4AC493;
    color: #ffffff;
    font-weight: bold;
    font-size: 16px;
    border-top-right-radius: 40px;
    border-bottom-right-radius: 40px;
  }

  .up-btn {
    padding: 0 10px;
    font-size: 20px;
    color: #4AC493;
  }

  .t-tag {
    margin: 10px;
  }
}

.grade-all {
  padding: 40px;
  font-size: 16px !important;

  .grade-p_info {
    display: flex;

    div {
      display: flex;
      padding: 0 20px;
      align-items: center;
      border: 1px solid #f8f8f8;

      img {
        width: 44px;
        height: 44px;
      }
    }
  }

  .grade-t {
    padding: 10px 0;
    text-align: center;
    background-color: #f8f8f8;
    font-size: 20px;
    font-weight: bold;
  }

  .grade-c {
    display: flex;

  }

  .grade-c_list {
    flex: 1;

    div {
      display: flex;

      span {
        padding: 10px 20px;
        flex: 1;
        border: 1px solid #f8f8f8;

        &.bad {
          color: red;
        }
      }
    }
  }
}

.bread_crumbs {
  display: flex;
  justify-content: space-between;
  width: 1486px;

  .bread {

  }
}


.search_temp {
  width: 1486px;
  height: 68px;
  background: #FFFFFF;
  border: 1px solid #F0F0F0;
  opacity: 1;
  border-radius: 10px;
  padding: 17px;
  display: inline-block;

  span{
    padding: 0 5px 0 25px;
  }

  .el-range-editor.el-input__inner{
    width: 250px;
    padding-right: 30px;
  }
  .el-input--mini .el-input__inner{
    width: 132px;
    padding: 0;
  }

}

</style>
